<?php
namespace app\index\controller;

use think\Controller;
use app\common\model\Category;

/**
 *  列表页控制器
 * Class ListPage
 * @package app\index\controller
 */
class ListPage extends Controller
{

	/**
	 * @return \think\response\View
	 */
	public function index()
    {
    	//接受cid参数
		$cid = input('param.cid');
		$price = input('param.price');
		//dump($price);
		$data = db('category')->select();
    	//1.面包屑导航
		$fatherData = $this->getFather($cid,$data);
		//数组翻转
		$fatherData = array_reverse($fatherData);
		$this->assign('fatherData',$fatherData);
		//2.根据参数处理数据
		$goodsData = $this->loadData($cid,$data,$price);
		$this->assign('goodsData',$goodsData);




    	return view();
    }

	/**
	 *加载列表页数据
	 */
	protected function loadData($cid,$data,$price)
	{
		//1.获取当前cid所有子集数据，包含自己
		$cids = (new Category)->getSon($cid,$data);//调用category模型中找子集方法
		$cids[] = $cid;//把自己追加进去

		if($price=='desc'){
			$goodsData = db('goods')->whereIn('cid',$cids)->order('shopprice desc')->select();
		}else{
			$goodsData = db('goods')->whereIn('cid',$cids)->order('shopprice asc')->select();
		}
		return $goodsData;
		//halt($cids);
		//dump($goodsData);
	}
	/**
	 * 递归找父级数据
	 * @param $cid		当前栏目cid
	 * @param $data		所有栏目数据
	 *
	 * @return array	所有父级数据包含自己
	 */
	protected function getFather( $cid, $data)
	{
		static $temp = [];
		foreach($data as $k=>$v){
			if($v['cid'] == $cid){
				$temp[] = $v;
				$this->getFather($v['pid'],$data);
			}
		}
		return $temp;
	}
}
